package com.ujson.uaa.utils;

import com.ujson.base.common.config.GlobalConfig;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

@Component
public class JwtUtils {

    public static GlobalConfig.Jwt jwt;
    public static Long expire = 2 * 3600 * 1000L;
    public static String secretKey = "qaz123!@#wsx";
    public static String roleKey = "roleKey";
    public static String authHeaderKey = "Authorization";

    @Autowired
    public void setGlobalConfig(GlobalConfig globalConfig) {
        JwtUtils.jwt = globalConfig.getJwt();
        defaultJwtConfig();
    }

    private void defaultJwtConfig() {
        if (Objects.nonNull(jwt)) {
            if (Objects.nonNull(jwt.getExpire())) {
                expire = jwt.getExpire();
            }
            if (Objects.nonNull(jwt.getSecretKey())) {
                secretKey = jwt.getSecretKey();
            }
            if (Objects.nonNull(jwt.getRoleKey())) {
                roleKey = jwt.getRoleKey();
            }
        }
    }

    public static void setExpire(Long expire) {
        JwtUtils.expire = expire;
    }
    public static void setSecretKey(String secretKey) {
        JwtUtils.secretKey = secretKey;
    }

    public static void setRoleKey(String roleKey) {
        JwtUtils.roleKey = roleKey;
    }

    public String createToken(String userName) {
        return Jwts.builder()
                .setSubject(userName)
                .setExpiration(new Date(System.currentTimeMillis() + expire))
                .signWith(SignatureAlgorithm.HS512, secretKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }

    public static String createToken(String userName, String role) {
        return Jwts.builder().setSubject(userName)
                .claim(roleKey, role)// 配置角色
                .setExpiration(new Date(System.currentTimeMillis() + expire))
                .signWith(SignatureAlgorithm.HS512, secretKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }

    public static String getUserNameFromToken(String token) {
        return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject();
    }

    public static String getUserRoleFromToken(String token) {
        Claims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();
        Object role = claims.get(roleKey);
        if (Objects.isNull(role)) {
            return null;
        }
        return role.toString();
    }
}
